package com.ssx.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ssx.entity.*;
import com.ssx.service.ICustomerService;
import com.ssx.service.ICustomershareService;
import com.ssx.service.ICustomervisitService;
import com.ssx.service.IEmployeesService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ssx
 * @since 2020-10-24
 */
@RestController
@RequestMapping("/employees")
public class EmployeesController {

    @Autowired
    private IEmployeesService employeesService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private ICustomervisitService customervisitService;
    @Autowired
    private ICustomershareService customershareService;

    /**
     * 获取当前用户的信息
     *
     * @param session
     * @return
     */
    @RequestMapping("/current")
    public String current(HttpSession session) {
        Employees emp = (Employees) session.getAttribute("emp");
        return JSON.toJSONString(emp);
    }

    /**
     * 登录
     *
     * @param employees
     * @return
     */
    @RequestMapping("/login")
    public String login(Employees employees,HttpSession session) {
        /*Employees one = employeesService.getOne(new QueryWrapper<Employees>().eq("username", employees.getUsername()).eq("password", employees.getPassword()));
        System.out.println(one);
        if (one != null) {
            return "success";
        } else {
            return "failed";
        }*/
        String flg="success";
        Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()){
            //把用户名和密码封装为UsernamePasswordToken对象
            UsernamePasswordToken token = new UsernamePasswordToken(employees.getUsername(), employees.getPassword());
            //rememberMe
//            token.setRememberMe(true);
            try {
                //执行登录
                currentUser.login(token);
//                session.setAttribute("emp", one);
            } catch (AuthenticationException e) {
                e.printStackTrace();
                flg="failed";
                System.out.println("登录失败");
            }
        }
        return flg;
    }

    @RequestMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "success";
    }
    /**
     * 修改密码，从前端获取id和password
     *
     * @return
     */
    @RequestMapping("/updatePassword")
    public String updatePassword(HttpServletRequest request) {
        String password = request.getParameter("password");
        Employees emp = (Employees) request.getSession().getAttribute("emp");

        String username=emp.getUsername();
        String hashAlgorithmName="MD5";
        Object salt= ByteSource.Util.bytes(username);
        int hashIterations=1024;
        SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, password, salt, hashIterations);
        String result = simpleHash.toString();

        emp.setPassword(result);
        boolean update = employeesService.updateById(emp);
        return update ? "success" : "failed";
    }

    /**
     * 删除一个客户
     *
     * @param id
     * @return
     */
    @RequestMapping("/delOneCus")
    public String delOneCus(int id, HttpServletRequest request) {
        Employees employees = (Employees) request.getSession().getAttribute("emp");
        int empid = employees.getEmpid();
        return customerService.delOneCus(id, empid) > 0 ? "success" : "failed";
    }

    /**
     * 登出
     *
     * @param session
     * @return
     */
    /*@RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("emp");
        return "success";
    }*/

    /**
     * 分页查拜访信息
     *
     * @param request
     * @return
     */
    @RequestMapping("/visitList")
    @RequiresPermissions(value = {"admin:select","emp:select","manager:select"},logical = Logical.OR)
    public String visitList(HttpServletRequest request) {
        //数据库第几条
        int offset = Integer.parseInt(request.getParameter("offset"));
        //每页大小
        int limit = Integer.parseInt(request.getParameter("limit"));
        //当前页
        int current = (offset / limit) + 1;
        Pager<Customervisit> pager = null;
        //查询条件
        String search = request.getParameter("search");
        Employees employees = (Employees) request.getSession().getAttribute("emp");
        int id = employees.getEmpid();
        //根据条件分页查询
        pager = new Pager<>(customervisitService.countFromEmp(search,id), customervisitService.listFromEmp(offset, limit, search, id));
        //返回json字符串
        pager.getRows().forEach(System.out::println);
        return JSON.toJSONString(pager);
    }

    @RequestMapping("/cusList")
    public String cusList(HttpServletRequest request) {
        //数据库第几条
        int offset = Integer.parseInt(request.getParameter("offset"));
        //每页大小
        int limit = Integer.parseInt(request.getParameter("limit"));
        //当前页
        int current = (offset / limit) + 1;
        Pager<Customer> pager = null;
        //查询条件
        String search = request.getParameter("search");
        Employees employees = (Employees) request.getSession().getAttribute("emp");
        int id = employees.getEmpid();
        //根据条件分页查询
        pager = new Pager<>(customershareService.countFromEmp(search,id),  customershareService.listFromEmp(offset, limit, search, id));

        pager.getRows().forEach(System.out::println);

        //返回json字符串
        return JSON.toJSONString(pager);
    }

    /**
     * 显示一条拜访记录
     *
     * @param id
     * @return
     */
    @RequestMapping("/showOneVisit")
    public String showOneVisit(int id) {
        Customervisit visit = customervisitService.getById(id);
        return JSON.toJSONString(visit);
    }

    /**
     * 显示一条客户记录
     *
     * @param id
     * @return
     */
    @RequestMapping("/showOneCus")
    public String showOneCus(Integer id) {
        Customer customer = customerService.showOneCus(id);
        return JSON.toJSONString(customer);
    }

    /**
     * 添加或修改客户
     *
     * @param modify
     * @param customer
     * @return
     */
    @RequestMapping("/editCus")
    public String editCus(int modify, Customer customer) {
        boolean flg;
        //0新增  1修改
        if (modify == 0) {
            flg = customerService.save(customer);
        } else {
            flg = customerService.updateById(customer);
        }
        return flg ? "success" : "failed";
    }

    @RequestMapping("/editVisit")
    public String editVisit( HttpServletRequest request) {
        int modify = Integer.parseInt(request.getParameter("modify"));
        int id;
        if (request.getParameter("id")!=null&&!"".equals(request.getParameter("id"))){
            id = Integer.parseInt(request.getParameter("id"));
        }else {
            id=0;
        }
        int cusId = Integer.parseInt(request.getParameter("cusId"));
        int empid = Integer.parseInt(request.getParameter("empid"));
        String content = request.getParameter("content");
        String date = request.getParameter("date");
        Customer customer = new Customer();
        customer.setCusId(cusId);
        Employees employees = new Employees();
        employees.setEmpid(empid);
        Customervisit customervisit = new Customervisit(id, customer,employees, content, date);

        System.out.println("==========");
        System.out.println(customervisit);
        boolean flg;
        //0新增  1修改
        if (id == 0) {
            flg = customervisitService.save(customervisit);
        } else {
            flg = customervisitService.updateById(customervisit);
        }
        System.out.println("flg"+flg);
        return flg ? "success" : "failed";
    }

    @RequestMapping("/share")
    public String share(int cusId,int empid){
        Customer customer = new Customer();
        customer.setCusId(cusId);
        Employees employees = new Employees();
        employees.setEmpid(empid);
        boolean flg=false;
        //分享表没有数据，则插入
        if (employeesService.getById(empid)!=null&&customershareService.getOne(new QueryWrapper<Customershare>().eq("cusId",cusId).eq("empid",empid))==null){
            flg= customershareService.save(new Customershare(0, customer, employees));
        }
        return flg?"success":"failed";
    }
}
